import asyncio, asyncpg

from async_db import async_timed

product_query = """
    select * from product as p 
    join sku as s on s.product_id = p.product_id
    join product_color as pc on pc.product_color_id = s.product_color_id
    join product_size as ps on ps.product_size_id = s.product_size_id
    where p.product_id = 100
"""


async def query_product(pool):
    async with pool.acquire() as connection:
        return await connection.fetchrow(product_query)


# 同步
@async_timed()
async def query_products_synchronously(pool, queries):
    return [await query_product(pool) for _ in range(queries)]


# 异步
@async_timed()
async def query_products_concurrnetly(pool, queries):
    queries = [query_product(pool) for _ in range(queries)]
    return await asyncio.gather(*queries)


async def main():
    async with asyncpg.create_pool(
            host="127.0.0.1",
            port=5432,
            user="around",
            password="zhouwei",
            database="products",
            min_size=6,
            max_size=6,
    ) as pool:
        # await asyncio.gather(
        #     query_product(pool),
        #     query_product(pool),
        # )

        await query_products_synchronously(pool, 10000)
        await query_products_concurrnetly(pool, 10000)


asyncio.run(main())
